package com.example.carrierapp.viewmodel.itemmodel

import android.databinding.BaseObservable
import android.databinding.Bindable
import android.graphics.Color
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.view.View
import com.example.carrierapp.config.mStartActivity
import com.example.carrierapp.ui.dialog.MAlertDialog
import com.example.carrierapp.ui.main.goodssource.details.GoodsSourceDetailsActivity
import com.example.carrierapp.util.AppUtil
import com.example.lb.fingerdemo.BR
import com.example.lb.fingerdemo.R
import com.google.gson.annotations.SerializedName

class ItemGoodsSourceModel : BaseObservable() {

    @SerializedName("id", alternate = ["lineId"])
    var id = 0 //线路Id

    var biddingId = 0 //招标id

    var bidMark = -1 //中标标识 -1未中标 0 默认 1 主 2 1分

    var maxPrice = 0f //最高限价 抢单价

    var freightVolume = 0f //预计运输量

    var robbingPattern = 0 //竟抢模式 1=竞价 2=考评分竞价 3=抢单

    var winPrice = 0f //承运商中标价

    var offer = 0f //承运商报价

    @Bindable
    var finalPrice = "0.0"
        set(value) {
            field = value
            notifyPropertyChanged(BR.finalPrice)
        }

    var adminName = "" //业务人员名称

    @Bindable
    var price: String? = null
        set(value) {
            field = value
            if (value.isNullOrEmpty()) {
                offer = 0f
                finalPrice = "0.0"
            } else {
                offer = value.toFloat()
                finalPrice = String.format("%.2f", value.toFloat() / 1.1f)
            }
            notifyPropertyChanged(BR.showUnit)
            notifyPropertyChanged(BR.price)
        }

    var carriers = 0 //承运家数

    var premium = 0f//承运商已缴纳保证金

    var deposit = 0//招标保证金

    var carNumber = 0//车数

    var settlementType = 0//结算方式 1=元/吨 2=元/车 3=元/吨/公里

    @SerializedName("prodPicPath")
    var icon = ""//产品图片路径

    @SerializedName("settlementTypeName")
    var unit = ""
        //结算方式名称
        get() = if (field.isEmpty()) when (settlementType) {
            2 -> "元/车"
            3 -> "元/吨/公里"
            else -> "元/吨"
        } else field

    var prodName = ""//招票保证金

    //详情展示单位
    var ditailsDisplay = ""
        get() = "$prodName   " + when (settlementType) {
            1 -> "${freightVolume}吨"
            2 -> "${carNumber}车/${freightVolume}吨"
            else -> "${freightVolume}吨/${distance}公里"
        }

    //货源展示单位
    var itemDisplay = ""
        get() = "$prodName | " + when (settlementType) {
            1 -> "${freightVolume}吨"
            2 -> "${carNumber}车/${freightVolume}吨"
            else -> "${freightVolume}吨/${distance}公里"
        }

    var mileage = 0f//里程

    private var distance = 0f//结算公里数

    private var serviceRate = 0f// 服务费率 or 服务费

    private var serviceCostType = 0//承运商服务费类型 1=不收取 2=按比例收取 3=按固定金额收取

    var serviceText = ""
        get() = when (serviceCostType) {
            2 -> "$serviceRate%"
            3 -> serviceRate.toString() + unit
            else -> ""
        }

    var midwayAddressList: MutableList<Address>? = null//中转站

    var hasMidWay = false
        get() = midwayAddressList.isNullOrEmpty().not()

    var showService = false
        get() = serviceCostType != 1

    //招标编码
    var bidCode = ""

    var lineCode = ""//线路编码 资源编码

    var showCode = ""
        get() = if (isMultiLine) {
            if (isCombination) bidCode else lineCode
        } else lineCode

    var startAddress = ""//装货地 市-区

    var startAddressDtl = ""//装货地详细地址

    var endAddress = ""//卸货地 市-区

    var endAddressDtl = ""//卸货地详细地址
    //备注
    var remark = ""
        get() = if (field.isNullOrEmpty()) "无" else field
    //常用线路标签
    var lineLable = ""
        get() = if (field.isNullOrEmpty()) "无" else field
    var isInsurance = false//是否购保


    @Bindable
    var isDetails = false
        set(value) {
            field = value
            notifyChange()
        }
    @Bindable
    @SerializedName("isShort")
    var showShort = false
        //是否短倒
        set(value) {
            field = value
            notifyPropertyChanged(BR.showShort)
        }

    //线路条数
    @SerializedName("totalLineCount")
    var lineNum = 0//组合招标线路数

    //是否组合招标
    @SerializedName("isGroupWinBid")
    var isCombination = false

    //是否多条线路
    private var isMultiLine = false

    //是否已报价
    var isPriced = false

    var showPrice = 0f
        get() = if (isDetails)
            if (bidMark == -1) offer else winPrice
        else
            if (isPriced) offer else maxPrice

    @Bindable
    var operationStr = ""
        get() = when {
            isMultiLine && isCombination -> if (isDetails) {
                showPriceTv = true
                "详情"
            } else {
                if (robbingPattern == 3) "抢单" else {
                    if (isPriced) "重新报价" else "报价"
                }
            }
            else -> {
                showCombination = false
                if (isDetails) {
                    showPriceTv = true
                    "详情"
                } else
                    if (robbingPattern == 3) "抢单" else {
                        if (carriers == 1) {
                            if (isPriced) {
                                showPriceTv = true
                                "重新报价"
                            } else "报价"
                        } else {
                            showButton = false
                            ""
                        }
                    }
            }
        }

    @Bindable
    var showUnit = false
        get() = robbingPattern == 3 && price.isNullOrEmpty().not()

    @Bindable
    var canInput = true
        get() = if (robbingPattern == 3) false else !isDetails

    var bidIcon = -1
        get() =
            when (bidMark) {
                1 -> R.mipmap.icon_master_the_winning
                2 -> R.mipmap.icon_one
                3 -> R.mipmap.icon_two
                4 -> R.mipmap.icon_three
                5 -> R.mipmap.icon_four
                else -> R.mipmap.icon_not_the_winning
            }


    //是否显示组合招标
    @Bindable
    var showCombination = true
        set(value) {
            field = value
            notifyPropertyChanged(BR.showCombination)
        }

    //是否显示按钮
    @Bindable
    var showButton = true
        set(value) {
            field = value
            notifyPropertyChanged(BR.showButton)
        }

    //是否显示价格
    @Bindable
    var showPriceTv = false
        set(value) {
            field = value
            notifyPropertyChanged(BR.showButton)
        }

    var showAmountNotice = false
        get() = (robbingPattern == 1 || robbingPattern == 2) && hasMidWay

    var showRobNotice = false
        get() = robbingPattern == 3 && hasMidWay

    var insText = ""
        get() = "每次运输时，中标承运商必须通过平台购买${premium}元/吨的货物保险"

    var priceLabel = ""
        get() = if (robbingPattern == 3) "抢单价格" else "含税报价($unit)"

    private val labelColor by lazy { Color.parseColor("#222222") }

    var amountNotice: SpannableString? = null
        get() {
            val sp = SpannableString("关于报价：$amountText")
            sp.setSpan(ForegroundColorSpan(labelColor), 0, 5, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
            return sp
        }
    var robNotice: SpannableString? = null
        get() {
            val sp = SpannableString("关于抢单价格：$robText")
            sp.setSpan(ForegroundColorSpan(labelColor), 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
            return sp
        }
    var settlementNotice: SpannableString? = null
        get() {
            val sp = SpannableString("关于结算：$settlementText")
            sp.setSpan(ForegroundColorSpan(labelColor), 0, 5, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
            return sp
        }

    private var amountText = ""
        get() = "该货源需要在中转地进行仓储加工，当您报价时，请务必按装货地至卸货地进行报价！"

    private var robText = ""
        get() = "抢单价格为装货地至卸货地的承运价格！"

    private var settlementText = ""
        get() = "在最终结算时，平台只以“${startAddressDtl}”到“${endAddressDtl}”的运量作为结算依据；其余路段产生的运量不纳入结算！"

    fun toOperation(view: View) {
        view.context?.apply {
            if (premium >= deposit)
                mStartActivity(GoodsSourceDetailsActivity::class.java,
                        Pair("robbingPattern", robbingPattern),
                        Pair("isCombination", isCombination),
                        Pair("isDetails", isDetails),
                        Pair("biddingId", biddingId),
                        Pair("lineId", id)
                )
            else {
                MAlertDialog.Builder(this)
                        .setMessage("该货源至少需要${deposit}元保证金！您已缴纳${premium}元，您可联系客服补缴后再来竞抢。")
                        .setTitle("竞抢失败")
                        .setNegativeButton("知道了", null)
                        .create().show()
            }
        }
    }

    class Address {
        var address = ""
        var addressDtl = ""
    }
}